/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @param {number} key
 * @return {TreeNode}
 */
var deleteNode = function (root, key) {
    return handleDeleteNode(root, key)
};

function handleDeleteNode(root, key) {
    if (root === null) return null
    if (root.val === key) {
        if (root.left === null && root.right === null) {
            return null
        }else if (root.left === null && root.right !== null) {
            return root.right
        }else if (root.left !== null && root.right === null) {
            return root.left
        }else{
            let temp = root.right
            while(temp.left !== null){
                temp = temp.left
            }
            temp.left = root.left
            return root.right
        }
    }

    if(key < root.val){
        root.left = handleDeleteNode(root.left,key)
    }else{
        root.right = handleDeleteNode(root.right,key)
    }
    return root
}


/**
 * 迭代遍历，维护当前相等节点的父节点，否则改变地址引用，直接赋值将不能改变root
 * @param {TreeNode} root
 * @param {number} key
 * @return {TreeNode}
 */
var deleteNode = function (root, key) {
    let temp = root, tempParent = null;
    while (temp !== null) {
        if (key < temp.val) {
            tempParent = temp
            temp = temp.left
        } else if (key > temp.val) {
            tempParent = temp
            temp = temp.right
        } else {
            break
        }
    }

    if (temp === null) return root
    if (tempParent === null) {
        // 头结点相等
        return deletOneNode(temp)
    }
    if(tempParent.left === temp){
        tempParent.left = deletOneNode(temp)
    }else{
        tempParent.right = deletOneNode(temp)
    }

    return root
};

function deletOneNode(temp) {
    if(temp.right === null) return temp.left
    let node = temp.right
    if (node !== null) {
        while (node.left !== null) {
            node = node.left
        }
        node.left = temp.left
    }
    return temp.right
}
